package com.heima.admin.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.heima.admin.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component  //让过滤器生效
@Slf4j
@Order(0) //控制过滤器执行顺序  值越小优先级越高
public class AuthorizeFilter implements GlobalFilter {
    private static List<String> urlList = new ArrayList<>();
    // 初始化白名单 url路径
    static {
        urlList.add("/login/in");
        urlList.add("/v2/api-docs");
    }

    /**
    * exchange 封装了 Request 请求 和 Response 响应 对象
     * chain 过滤器链  放行请求
    * */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象
                //ServerHttpRequest  点进去属于异步框架的Request
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2:判断用户的请求路径是否需要拦截
        String reqUrl = request.getURI().getPath(); // /admin/login/in
        for (String url : urlList) {
            //不需要拦截直接放行
            if(reqUrl.contains(url)){
                return chain.filter(exchange);
            }
        }

        //3:获取请求头中的token信息   (请求头信息可以写多个token  token:11 token:22  getFIRST()获取第一个token信息)
        String token = request.getHeaders().getFirst("token");
        //如果没有token直接终止请求  并将响应状态设置为  401
        if(StringUtils.isBlank(token)){
           response.setStatusCode(HttpStatus.UNAUTHORIZED);  //设置状态码,给前端显示状态信息
          return  response.setComplete();
            //改造优化
           // return writeMessage(exchange,"未携带token");
        }

        //4: 解析token   (claimsBody载荷信息)
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            // -1：有效，0：有效，1：过期，2：过期
            int i = AppJwtUtil.verifyToken(claimsBody);
            if(i<1){
            //4.1 解析成功 获取token中的用户id 将用户id重新设置到请求头中  放行请求
                Object id = claimsBody.get("id");
                //mutate() 改变request本身的值
                request.mutate().header("userId",String.valueOf(id));
                //改变exchange本身的值
                exchange.mutate().request(request);
                log.info("网关解析token成功  当前登录用户id: {}", id);
                return chain.filter(exchange);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("网关解析token失败  异常原因: {}", e.getMessage());
        }
        //解析失败终止请求
     /*   response.setStatusCode(HttpStatus.UNAUTHORIZED);  //设置状态码,给前端显示状态信息
        return  response.setComplete();*/
        //改造优化
     return writeMessage(exchange,"解析token失败");
    }
    /**
     * 返回错误提示信息
     * @return
     */
    private Mono<Void> writeMessage(ServerWebExchange exchange, String message) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpStatus.UNAUTHORIZED.value());
        map.put("errorMessage", message);
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //设置状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //response.setStatusCode(HttpStatus.OK);
        //设置返回类型
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        //设置返回数据
        DataBuffer buffer = response.bufferFactory().wrap(JSON.toJSONBytes(map));
        //响应数据回浏览器
        return response.writeWith(Flux.just(buffer));
    }
}
